import pandas as pd
def main():
    file_path = 'stockdata.xlsx'
    read_excel_and_analyze(file_path)
def read_excel_and_analyze(file_path):
    try:
        # 读取 Excel 文件
        df = pd.read_excel(file_path)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到，请检查路径。")
        return
    except Exception as e:
        print(f"读取文件时发生异常: {e}")
        return

    # 按股票代码分组并统计频数
    freq = df.groupby('股票代码').size()

    # 计算总样本数
    total_count = len(df)

    # 计算频率
    freq_rate = freq / total_count

    # 将结果转换为 DataFrame
    result_df = pd.DataFrame({
        '股票代码': freq.index,
        '词频': freq_rate
    })

    # 保存为 CSV 文件
    try:
        result_df.to_csv('code.csv', index=False)
    except Exception as e:
        print(f"保存 CSV 文件时发生异常: {e}")



if __name__ == "__main__":
    main()

